package com.samoilovich.belarustoday.handlers;

import android.util.Log;

import com.samoilovich.belarustoday.basefragments.BaseFragment;
import com.samoilovich.belarustoday.basefragments.NewsContentBaseFragment;
import com.samoilovich.belarustoday.basefragments.NewsListBaseFragment;
import com.samoilovich.belarustoday.datemodel.CategoryModel;
import com.samoilovich.belarustoday.datemodel.NewsModel;
import com.samoilovich.belarustoday.basefragments.NewsBaseFragment;
import com.samoilovich.belarustoday.tools.Utility;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;

public class NewsHandler {
    private final String TAG = getClass().getName();
    private final String CATEGORIES_URL = "http://belarustoday.by/belarus/api/newscategory.php?category=%s";
    private final String CATEGORY_NEWS_LIST_URL = "http://belarustoday.by/belarus/api/getnews.php?category=%s";
    private final String CATEGORY_MORE_LIST_URL = "http://belarustoday.by/belarus/api/getnews.php?category=%s&count=%s&last=%s";
    private final String NEWS_CONTENT_URL = "http://belarustoday.by/belarus/api/getnewsitem.php?newsid=%s";

    private final String ID = "news_category_id";
    private final String NAME = "news_category_name";
    private final String DESCRIPTION = "news_category_description";
    private final String LINK = "news_category_link";
    private final String IMAGE_LINK = "news_category_image";
    private final String TYPE = "news_category_type";

    private final String NEWS_ID = "news_id";
    private final String NEWS_TITLE = "news_title";
    private final String NEWS_IMAGE_LINK = "news_image";
    private final String NEWS_CATEGORY = "news_category";
    private final String NEWS_TIME = "news_time";
    private final String NEWS_CATEGORY_ID = "news_category_id";
    private final String NEWS_LINK = "news_link";
    private final String NEWS_DESCRIPTION = "news_description";


    private static NewsHandler sInstance;
    private ArrayList<CategoryModel> mCategories;
    private ArrayList<NewsModel> mNews;

    private NewsHandler() { 
    	mCategories = new ArrayList<CategoryModel>();
        mNews = new ArrayList<NewsModel>();
    }

    public static NewsHandler getInstance() {
        if (sInstance == null) {
            sInstance = new NewsHandler();
        }

        return sInstance;
    }

    public void getCategories(final NewsBaseFragment listener, final int categoryId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpResponse response;
                HttpClient client;
                HttpParams params;

                try {
                    params = Utility.createHttpParams();
                    client = new DefaultHttpClient(params);
                    response = client.execute(new HttpGet(String.format(CATEGORIES_URL, categoryId)));
                    InputStream stream = response.getEntity().getContent();
                    String json = Utility.convertStreamToString(stream);
                    parseCategoriesJSON(json);
                    listener.update(mCategories);
                    Log.d(TAG, json);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }).start();
    }

    public void getCategoryNewsList(final BaseFragment listener, final long categoryId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpResponse response;
                HttpClient client;
                HttpParams params;

                try {
                    params = Utility.createHttpParams();
                    client = new DefaultHttpClient(params);
                    response = client.execute(new HttpGet(String.format(CATEGORY_NEWS_LIST_URL, categoryId)));
                    InputStream stream = response.getEntity().getContent();
                    String json = Utility.convertStreamToString(stream);
                    parseCategoryNewsListJSON(true, json);
                    listener.updateCategoryContent(mNews);
                    Log.d(TAG, json);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }).start();
    }

    public void getMoreCategoryNews(final NewsListBaseFragment listener, final long categoryId, final String count, String time) {
        final String correctTime = time.replace(" ", "%20");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpResponse response;
                HttpClient client;
                HttpParams params;

                try {
                    params = Utility.createHttpParams();
                    client = new DefaultHttpClient(params);
                    String str = String.format(CATEGORY_MORE_LIST_URL, categoryId, count, correctTime);
                    response = client.execute(new HttpGet(str));
                    InputStream stream = response.getEntity().getContent();
                    String json = Utility.convertStreamToString(stream);
                    parseCategoryNewsListJSON(false, json);
                    listener.updateCategoryContent(mNews);
                    Log.d(TAG, json);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }).start();
    }

    public void getNewsContent(final NewsContentBaseFragment listener, final long newsId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpResponse response;
                HttpClient client;
                HttpParams params;

                try {
                    params = Utility.createHttpParams();
                    client = new DefaultHttpClient(params);
                    response = client.execute(new HttpGet(String.format(NEWS_CONTENT_URL, newsId + "")));
                    InputStream stream = response.getEntity().getContent();
                    String json = Utility.convertStreamToString(stream);
                    NewsModel newsModel =  parseNewsContentJSON(json, newsId);
                    listener.updateNewsContent(newsModel);
                    Log.d(TAG, json);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }).start();
    }

	// -----------------------------------------------------------------------------------
	// -----------------------------------------------------------------------------------
    private void parseCategoriesJSON(String json) {
    	JSONObject temp;
    	CategoryModel category;
    	
    	try {
    		mCategories = new ArrayList<CategoryModel>();
    		JSONArray array = new JSONArray(json);
    		for (int i = 0; i < array.length(); i++) {
    			category = new CategoryModel();
				temp = array.getJSONObject(i);
				category.setId(temp.getLong(ID));
				category.setName(temp.getString(NAME));
				category.setDescription(temp.getString(DESCRIPTION));
				category.setLink(temp.getString(LINK));
				category.setImageLink(temp.getString(IMAGE_LINK));
				category.setType(temp.getInt(TYPE));
				mCategories.add(category);
			}
    	
    	} catch (Exception exp) {
    		exp.printStackTrace();
    	}
    }

    private void parseCategoryNewsListJSON(boolean cleanFlag, String json) {
        JSONObject temp;
        NewsModel category;

        try {
            if (cleanFlag) {
                mNews = new ArrayList<NewsModel>();
            } else {
               mNews = new ArrayList<NewsModel>(mNews);
            }
            JSONArray array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                category = new NewsModel();
                temp = array.getJSONObject(i);
                category.setId(temp.getLong(NEWS_ID));
                category.setTitle(temp.getString(NEWS_TITLE));
                category.setTime(temp.getString(NEWS_TIME));
                category.setCategory(temp.getString(NEWS_CATEGORY));
                category.setImageLink(temp.getString(NEWS_IMAGE_LINK));
                category.setCategoryId(temp.getInt(NEWS_CATEGORY_ID));
                mNews.add(category);
            }

        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }

    private NewsModel parseNewsContentJSON(String json, long id) {
        NewsModel model;

        try {
            JSONObject obj = new JSONObject(json);
            model = new NewsModel();
            model.setId(id);
            model.setTitle(obj.getString(NEWS_TITLE));
            model.setTime(obj.getString(NEWS_TIME));
            model.setCategory(obj.getString(NEWS_CATEGORY));
            model.setImageLink(obj.getString(NEWS_IMAGE_LINK));
            model.setLink(obj.getString(NEWS_LINK));
            model.setDescription(obj.getString(NEWS_DESCRIPTION));

            return model;
        } catch (Exception exp) {
            exp.printStackTrace();
        }

        return null;
    }
    
}
